package us.nchu.onlineJudger.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    public static String fileToMd5(String addr) throws IOException {
        FileInputStream fin = new FileInputStream(new File(addr));
        try {
            byte[] bytes = new byte[fin.available()];
            fin.read(bytes);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(bytes);
            return Trans(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String StringToMd5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.update(str.getBytes());
        byte[] bytes1 = md5.digest();
        return Trans(bytes1);

    }

    private static String Trans(byte[] bytes) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String s = Integer.toHexString(bytes[i] & 0xff);
            s = (s.length() < 2) ? "0" + s : s;
            buffer.append(s);
        }
        return buffer.toString();
    }
}
